package org.amicofragile.web.spring.mvc;

import javax.servlet.http.HttpSession;

import org.amicofragile.websample.model.GreetingsComposer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloController {
	public HelloController() {
		System.out.println("Init");
	}
	
	@Autowired
	private GreetingsComposer composer;
	
	@RequestMapping(value="/msg",method={RequestMethod.GET})
	public ModelAndView message(@RequestParam(value="to", required=false) String target, HttpSession session) {
		if(target == null) {
			target = (String)session.getAttribute("previous");
			if(target == null) {
				target = "Spring MVC";
			}
		} else {
			session.setAttribute("previous", target);
		}
		String message = composer.composeMessage(target);
		ModelAndView modelAndView = new ModelAndView("hello");
		modelAndView.addObject("_message", message);
		return modelAndView;
	}
	
	@RequestMapping(value="/invalidate",method={RequestMethod.GET})
	public String invalidateSession(HttpSession session) {
		session.invalidate();
		return "invalidation-ok";
	}
}
